package com.abocode.aichat.getway.endpoint;

import com.abocode.aichat.getway.handler.GatewayServerInboundHandler;
import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.worker.Worker;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

/**
 * Created by franky-14.
 */
public class GatewayChannelHandlerRegister extends ChannelInitializer {
    private ServerRuntimeContext serverRuntimeContext;
    private Worker worker;

    public GatewayChannelHandlerRegister(ServerRuntimeContext serverRuntimeContext, Worker worker) {
        this.serverRuntimeContext = serverRuntimeContext;
        this.worker = worker;
    }

    private static final int IDEL_TIME_OUT = 10;
    private static final int READ_IDEL_TIME_OUT = 30;
    private static final int WRITE_IDEL_TIME_OUT = 30;

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast("timeout", new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, IDEL_TIME_OUT));
        pipeline.addLast("handler", new GatewayServerInboundHandler(serverRuntimeContext, worker));
    }
}
